import axios from "axios";

const request = axios.create({
  baseURL: "http://47.108.128.216:5000",
  timeout: 3000,
});

// json 请求
// request.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

request.interceptors.request.use((config) => {
  // Do something before request is sent
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["Authorization"] = "Bearer " + token;
  }
  return config;
});

request.interceptors.response.use(
  (response) => {
    let localhost = window.location.href.split("/");
    localhost.splice(localhost.length - 1, 1);
    localhost = localhost.join("/");
    // Do something with response data
    if (response.data.status === 401) {
      // 401 代表 token 失效，清除本地存储的 token 并跳转到登录页面
      window.location.href = localhost + '/loginFailure'
    }
    return response.data;
  },
  (error) => {
    // Do something with response error
    return Promise.reject(error);
  }
);

export default request;
